package buru.server.netty.rest;

import buru.server.netty.NettyHandlerJerseyContainer;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import org.glassfish.jersey.server.ApplicationHandler;
import org.glassfish.jersey.server.ResourceConfig;


class HttpServerPipelineFactory extends ChannelInitializer<SocketChannel> {
    private NettyHandlerJerseyContainer jerseyHandler;

    public HttpServerPipelineFactory(final Class<?>... classes) {
        this.jerseyHandler = getJerseyHandler(classes);
    }

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

//        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpResponseEncoder());
        pipeline.addLast(new HttpRequestDecoder());
        pipeline.addLast(new HttpContentCompressor());


//                            ch.pipeline().addLast(new ChunkedWriteHandler());
//                            ch.pipeline().addLast(new FileServerHandler());
//        pipeline.addLast(new ChunkedWriteHandler());
//                            pipeline.addLast(new HttpServerInboundHandler());
        //用于写一个ChunkedInput
//                            ch.pipeline().addLast(new WriteStreamHandler());

        pipeline.addLast(jerseyHandler);
    }

//    public ChannelPipeline getPipeline() throws Exception
//    {
//        ChannelPipeline pipeline = Channels.pipeline();
//        pipeline.addLast("decoder", new HttpRequestDecoder());
//        pipeline.addLast("encoder", new HttpResponseEncoder());
//        pipeline.addLast("jerseyHandler", jerseyHandler);
//        return pipeline;
//    }

    private NettyHandlerJerseyContainer getJerseyHandler(final Class<?>... classes) {
        ResourceConfig rcf = new ResourceConfig();
//        rcf.registerClasses(classes);
        rcf.packages("info.ibruce");
//        rcf.setProperties(Collections.singletonMap(NettyHandlerContainer.PROPERTY_CONTEXT_PATH, "abc"));

        return new NettyHandlerJerseyContainer(new ApplicationHandler(rcf));
    }
}
